package com.google.code.mochaccino.framework.xml.xpath;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.jaxen.JaxenException;
import org.jaxen.dom.DOMXPath;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Jaxen Implementation of the XPathEngine
 *
 *
 */
public class XPathEngineJaxen extends XPathEngine {

	/** Constructor */
	public XPathEngineJaxen() {
	}

	/** Select the Node Represented by that XPath */
	@Override
	public Node selectNode( Node node, String xpath ) throws XPathEngineException {
		try {
			return (Node) compile( xpath ).selectSingleNode( node );
		} catch ( JaxenException e ) {
			throw new XPathEngineException( e.getMessage(), e );
		}
	}

	/** Select the Nodes Represented by that XPath */
	@Override
	public NodeList selectNodeList( Node node, String xpath ) throws XPathEngineException {
		try {
			return new DOMNodeListImpl( compile( xpath ).selectNodes( node ) );
		} catch ( JaxenException e ) {
			throw new XPathEngineException( e.getMessage(), e );
		}
	}

	/**
	 * Select the Value of the XPath. If the XPath represent something else than an Attribute or a
	 * TextNode, then there will be an XPathEngineException sent to the user.
	 */
	@Override
	public String selectNodeValue( Node node, String xpath ) throws XPathEngineException {
		try {
			return compile( xpath ).stringValueOf( node );
		} catch ( JaxenException e ) {
			throw new XPathEngineException( e.getMessage(), e );
		}
	}

	/** Compile */
	protected DOMXPath compile( String xpath ) throws XPathEngineException {
		try {
			return new DOMXPath( xpath );
		} catch ( JaxenException e ) {
			throw new XPathEngineException( e.getMessage(), e );
		}
	}
}
